package com.atguigu.userprofile.util;

import com.atguigu.userprofile.bean.TagInfo;
import com.atguigu.userprofile.constant.ConstCode;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 负责MySQL数据的增删改查
 */
public class MySqlUtil {

    //private static String url = "jdbc:mysql://hadoop102:3306/user_profile_manager0620";
    //private static String url = MyPropsUtil.get("mysql.url");
    private static String url = MyPropsUtil.get(ConstCode.MYSQL_URL);
    private static String username = MyPropsUtil.get(ConstCode.MYSQL_USERNAME);
    private static String password = MyPropsUtil.get(ConstCode.MYSQL_PASSWORD);

    /**
     *  完成查询某张表，将结果封装成T类型
     * @param <T>
     * @return
     */
    public static <T> T selectOne(String querySql  , Class<T> cls ,Boolean isUnderScoreToCamel ){
        List<T> selectList = selectList(querySql, cls , isUnderScoreToCamel);
        if(!selectList.isEmpty()){
            return selectList.get(0);
        }else{
            return null ;
        }
    }

    /**
     * 完成查询某张表， 将结果封装成T类型的对象
     * @param querySql
     * @param cls
     * @param <T>
     * @return
     *
     * JDBC步骤:
     * 1. 注册驱动
     * 2. 获取连接
     * 3. 编写SQL
     * 4. 预编译SQL
     * 5. 设置参数
     * 6. 执行SQL
     * 7. 处理结果
     * 8. 关闭连接
     */
    public static <T> List<T> selectList(String querySql ,Class<T> cls , Boolean isUnderScoreToCamel){
        ArrayList<T> resultList = new ArrayList<>();
        Connection connection = null ;
        PreparedStatement preparedStatement = null ;
        ResultSet resultSet = null ;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, username, password);
            preparedStatement = connection.prepareStatement(querySql);
            //结果集
            resultSet = preparedStatement.executeQuery();
            //获取元数据(包含查询的列信息)
            ResultSetMetaData metaData = resultSet.getMetaData();
            while(resultSet.next()){
                //将查询的每条数据封装成一个T对象
                T obj = cls.newInstance();  //要求T类中有无参数构造器
                //获取列信息:列的个数
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    //获取列信息: 列的名字
                    String columnName = metaData.getColumnLabel(i);
                    //获取列的值
                    Object columnValue = resultSet.getObject(columnName);

                    //将列的名字换算成对象属性的名字
                    String fieldName = null;
                    if(isUnderScoreToCamel){
                        // tag_code => tagCode
                        fieldName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName) ;
                    }else{
                        fieldName = columnName ;
                    }

                    //通过beanUtil将列的值赋值到对象的属性上
                    BeanUtils.copyProperty(obj , fieldName  , columnValue);
                }

                // 将处理好对象添加到集合中
                resultList.add(obj);
            }

            return resultList ;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询Mysql失败:" + e.getMessage());
        }finally {
            try {
                resultSet.close();
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("关联资源失败: " + e.getMessage());
            }
        }
    }


    public static void main(String[] args) {
        String sql = "select id , tag_code , tag_name , tag_level , parent_tag_id ,tag_type ," +
                " tag_value_type ,tag_value_limit ,tag_value_step , tag_task_id , tag_comment ," +
                " update_time ,create_time from tag_info  where id = 7" ;
        TagInfo tagInfo = selectOne(sql, TagInfo.class, true);

        System.out.println(tagInfo);
    }



}
